<template>
  <div class="space-container">
    <!-- 个人信息卡片 -->
    <div class="profile-card">
      <div class="profile-header">
        <div class="avatar-section">
          <div class="avatar-wrapper">
            <el-avatar :size="120" :src="currentUser?.avatar">
              {{ currentUser?.nickname?.charAt(0) || 'U' }}
            </el-avatar>
            <div class="avatar-overlay" @click="changeAvatar">
              <el-icon>
                <Camera />
              </el-icon>
              <span>更换头像</span>
            </div>
          </div>

          <div class="status-selector">
            <el-select v-model="userStatus" @change="updateUserStatus">
              <el-option v-for="status in statusOptions" :key="status.value" :label="status.label"
                :value="status.value">
                <div class="status-option">
                  <div class="status-dot" :class="status.value === 1 ? 'online' : 'offline'" />
                  <span>{{ status.label }}</span>
                </div>
              </el-option>
            </el-select>
          </div>
        </div>

        <div class="profile-info">
          <div class="info-item">
            <label>昵称</label>
            <div class="info-content">
              <span v-if="!editingNickname" class="info-text" @click="startEditNickname">
                {{ currentUser?.nickname || '未设置' }}
              </span>
              <el-input v-else v-model="editNickname" size="small" @blur="saveNickname" @keyup.enter="saveNickname"
                @keyup.esc="cancelEditNickname" ref="nicknameInputRef" />
              <el-button v-if="!editingNickname" text size="small" @click="startEditNickname">
                <el-icon>
                  <Edit />
                </el-icon>
              </el-button>
            </div>
          </div>

          <div class="info-item">
            <label>用户名</label>
            <div class="info-content">
              <span class="info-text">{{ currentUser?.username || '未设置' }}</span>
            </div>
          </div>

          <div class="info-item">
            <label>个性签名</label>
            <div class="info-content">
              <span v-if="!editingSignature" class="info-text" @click="startEditSignature">
                {{ currentUser?.signature || '这个人很懒，什么都没留下' }}
              </span>
              <el-input v-else v-model="editSignature" type="textarea" :rows="2" size="small" @blur="saveSignature"
                @keyup.esc="cancelEditSignature" ref="signatureInputRef" />
              <el-button v-if="!editingSignature" text size="small" @click="startEditSignature">
                <el-icon>
                  <Edit />
                </el-icon>
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 功能设置区域 -->
    <div class="settings-section">
      <div class="settings-card">
        <h3 class="card-title">聊天设置</h3>
        <div class="setting-item">
          <div class="setting-info">
            <span class="setting-label">消息提示音</span>
            <span class="setting-desc">接收消息时播放提示音</span>
          </div>
          <el-switch v-model="settings.messageSound" />
        </div>

        <div class="setting-item">
          <div class="setting-info">
            <span class="setting-label">桌面通知</span>
            <span class="setting-desc">在桌面显示消息通知</span>
          </div>
          <el-switch v-model="settings.desktopNotification" />
        </div>

        <div class="setting-item">
          <div class="setting-info">
            <span class="setting-label">自动回复</span>
            <span class="setting-desc">离开时自动回复消息</span>
          </div>
          <el-switch v-model="settings.autoReply" />
        </div>
      </div>

      <div class="settings-card">
        <h3 class="card-title">隐私设置</h3>
        <div class="setting-item">
          <div class="setting-info">
            <span class="setting-label">显示在线状态</span>
            <span class="setting-desc">让好友看到您的在线状态</span>
          </div>
          <el-switch v-model="settings.showOnlineStatus" />
        </div>

        <div class="setting-item">
          <div class="setting-info">
            <span class="setting-label">允许陌生人添加</span>
            <span class="setting-desc">允许陌生人发送好友请求</span>
          </div>
          <el-switch v-model="settings.allowStrangerAdd" />
        </div>

        <div class="setting-item">
          <div class="setting-info">
            <span class="setting-label">消息已读回执</span>
            <span class="setting-desc">发送消息已读状态给对方</span>
          </div>
          <el-switch v-model="settings.readReceipt" />
        </div>
      </div>

      <div class="settings-card">
        <h3 class="card-title">账户管理</h3>
        <div class="account-actions">
          <el-button @click="exportChatHistory">
            <el-icon>
              <Download />
            </el-icon>
            导出聊天记录
          </el-button>

          <el-button @click="clearAllData">
            <el-icon>
              <Delete />
            </el-icon>
            清空所有数据
          </el-button>

          <el-button type="danger" @click="logout">
            <el-icon>
              <SwitchButton />
            </el-icon>
            退出登录
          </el-button>
        </div>
      </div>
    </div>

    <!-- 头像上传对话框 -->
    <el-dialog v-model="avatarDialogVisible" title="更换头像" width="400px">
      <div class="avatar-upload">
        <el-upload class="avatar-uploader" action="#" :show-file-list="false" :before-upload="beforeAvatarUpload"
          :http-request="handleAvatarUpload">
          <img v-if="previewAvatar" :src="previewAvatar" class="avatar-preview" />
          <el-icon v-else class="avatar-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>
        <div class="upload-tips">
          <p>支持 JPG、PNG 格式，文件大小不超过 2MB</p>
        </div>
      </div>

      <template #footer>
        <el-button @click="avatarDialogVisible = false">取消</el-button>
        <el-button type="primary" :disabled="!previewAvatar" @click="confirmAvatarChange">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, reactive, nextTick, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Camera, Edit, Download, Delete, SwitchButton, Plus
} from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/counter'

const router = useRouter()
const userStore = useUserStore()

// 响应式数据
const editingNickname = ref(false)
const editingSignature = ref(false)
const editNickname = ref('')
const editSignature = ref('')
const avatarDialogVisible = ref(false)
const previewAvatar = ref('')
const userStatus = ref(1) // 默认在线状态

// 引用
const nicknameInputRef = ref()
const signatureInputRef = ref()

// 计算属性
const currentUser = computed(() => userStore.currentUser)

// 状态选项
const statusOptions = [
  { value: 1, label: '在线' },
  { value: 0, label: '离线' }
]

// 设置数据
const settings = reactive({
  messageSound: true,
  desktopNotification: true,
  autoReply: false,
  showOnlineStatus: true,
  allowStrangerAdd: true,
  readReceipt: true
})

// 开始编辑昵称
const startEditNickname = () => {
  editNickname.value = currentUser.value?.nickname || ''
  editingNickname.value = true
  nextTick(() => {
    nicknameInputRef.value?.focus()
  })
}

// 保存昵称
const saveNickname = () => {
  if (editNickname.value.trim()) {
    userStore.updateUserInfo({ nickname: editNickname.value.trim() })
    ElMessage.success('昵称更新成功')
  }
  editingNickname.value = false
}

// 取消编辑昵称
const cancelEditNickname = () => {
  editingNickname.value = false
  editNickname.value = ''
}

// 开始编辑签名
const startEditSignature = () => {
  editSignature.value = currentUser.value?.signature || ''
  editingSignature.value = true
  nextTick(() => {
    signatureInputRef.value?.focus()
  })
}

// 保存签名
const saveSignature = () => {
  userStore.updateUserInfo({ signature: editSignature.value.trim() })
  ElMessage.success('个性签名更新成功')
  editingSignature.value = false
}

// 取消编辑签名
const cancelEditSignature = () => {
  editingSignature.value = false
  editSignature.value = ''
}

// 更新用户状态
const updateUserStatus = async (status: number) => {
  try {
    await userStore.updateStatus(status)
    ElMessage.success(`状态已更新为${statusOptions.find(s => s.value === status)?.label}`)
  } catch (error) {
    ElMessage.error('状态更新失败，请重试')
    console.error('状态更新失败:', error)
  }
}

// 更换头像
const changeAvatar = () => {
  avatarDialogVisible.value = true
  previewAvatar.value = ''
}

// 头像上传前检查
const beforeAvatarUpload = (file: File) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 处理头像上传
const handleAvatarUpload = (options: any) => {
  const file = options.file
  const reader = new FileReader()

  reader.onload = (e) => {
    previewAvatar.value = e.target?.result as string
  }

  reader.readAsDataURL(file)
}

// 确认头像更改
const confirmAvatarChange = () => {
  if (previewAvatar.value) {
    userStore.updateUserInfo({ avatar: previewAvatar.value })
    ElMessage.success('头像更新成功')
    avatarDialogVisible.value = false
  }
}

// 导出聊天记录
const exportChatHistory = () => {
  ElMessage.info('导出功能开发中...')
}

// 清空所有数据
const clearAllData = async () => {
  try {
    await ElMessageBox.confirm(
      '此操作将清空所有聊天记录和设置，是否继续？',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    // 清空数据逻辑
    ElMessage.success('数据已清空')
  } catch {
    ElMessage.info('已取消操作')
  }
}

// 退出登录
const logout = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要退出登录吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    userStore.logout()
    ElMessage.success('已退出登录')
    router.push('/login')
  } catch {
    ElMessage.info('已取消操作')
  }
}

// 组件挂载时初始化
onMounted(() => {
  if (currentUser.value) {
    userStatus.value = currentUser.value.status
  }
})
</script>

<style scoped lang="scss">
.space-container {
  height: 100vh;
  background: var(--bg-secondary);
  overflow-y: auto;
  padding: var(--spacing-lg);
}

.profile-card {
  background: var(--bg-primary);
  border-radius: var(--radius-xl);
  box-shadow: var(--shadow-lg);
  border: 1px solid var(--border-light);
  margin-bottom: var(--spacing-lg);
  overflow: hidden;

  .profile-header {
    display: flex;
    padding: 30px;
    gap: 30px;

    .avatar-section {
      display: flex;
      flex-direction: column;
      align-items: center;
      gap: 20px;

      .avatar-wrapper {
        position: relative;
        cursor: pointer;

        .avatar-overlay {
          position: absolute;
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
          background: rgba(0, 0, 0, 0.5);
          border-radius: 50%;
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          opacity: 0;
          transition: opacity 0.3s ease;
          color: white;
          font-size: 12px;

          .el-icon {
            font-size: 24px;
            margin-bottom: 4px;
          }
        }

        &:hover .avatar-overlay {
          opacity: 1;
        }
      }

      .status-selector {
        width: 120px;

        :deep(.el-select) {
          width: 100%;

          .el-input__wrapper {
            border-radius: 20px;
          }
        }
      }
    }

    .profile-info {
      flex: 1;
      display: flex;
      flex-direction: column;
      gap: 20px;

      .info-item {
        label {
          display: block;
          font-weight: 500;
          color: #606266;
          margin-bottom: 8px;
          font-size: 14px;
        }

        .info-content {
          display: flex;
          align-items: center;
          gap: 8px;

          .info-text {
            flex: 1;
            padding: 8px 12px;
            background: #f5f7fa;
            border-radius: 6px;
            cursor: pointer;
            transition: background-color 0.2s ease;
            min-height: 20px;
            line-height: 20px;

            &:hover {
              background: #ebeef5;
            }
          }
        }
      }
    }
  }
}

.settings-section {
  display: flex;
  flex-direction: column;
  gap: 20px;

  .settings-card {
    background: white;
    border-radius: 12px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    padding: 24px;

    .card-title {
      font-size: 18px;
      font-weight: 600;
      color: #262626;
      margin: 0 0 20px 0;
      padding-bottom: 12px;
      border-bottom: 1px solid #f0f2f5;
    }

    .setting-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 16px 0;
      border-bottom: 1px solid #f8f9fa;

      &:last-child {
        border-bottom: none;
      }

      .setting-info {
        flex: 1;

        .setting-label {
          display: block;
          font-weight: 500;
          color: #262626;
          font-size: 14px;
          margin-bottom: 4px;
        }

        .setting-desc {
          display: block;
          font-size: 12px;
          color: #8c8c8c;
          line-height: 1.4;
        }
      }
    }

    .account-actions {
      display: flex;
      gap: 12px;
      flex-wrap: wrap;

      .el-button {
        flex: 1;
        min-width: 140px;
      }
    }
  }
}

// 状态选项样式
.status-option {
  display: flex;
  align-items: center;
  gap: 8px;

  .status-dot {
    width: 8px;
    height: 8px;
    border-radius: 50%;

    &.online {
      background: #52c41a;
    }

    &.offline {
      background: #d9d9d9;
    }
  }
}

// 头像上传样式
.avatar-upload {
  text-align: center;

  .avatar-uploader {
    :deep(.el-upload) {
      border: 2px dashed #d9d9d9;
      border-radius: 8px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: border-color 0.3s ease;
      width: 200px;
      height: 200px;
      display: flex;
      align-items: center;
      justify-content: center;

      &:hover {
        border-color: #1890ff;
      }
    }

    .avatar-preview {
      width: 200px;
      height: 200px;
      object-fit: cover;
      border-radius: 6px;
    }

    .avatar-uploader-icon {
      font-size: 48px;
      color: #8c8c8c;
    }
  }

  .upload-tips {
    margin-top: 12px;

    p {
      margin: 0;
      font-size: 12px;
      color: #8c8c8c;
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .space-container {
    padding: 12px;
  }

  .profile-card .profile-header {
    flex-direction: column;
    align-items: center;
    text-align: center;
    gap: 20px;
  }

  .settings-section .settings-card .account-actions {
    flex-direction: column;

    .el-button {
      min-width: auto;
    }
  }
}
</style>
